/*
 * xiaomi.cpp
 *
 *  Created on: Dec 27, 2013
 *      Author: killerg
 */




#include "../bill_deps.h"
#include "platform_deps.h"

static const char* appId = "23752";
static const char* appKey = "71f76a0c-b11f-6807-16bb-5305f2d0685a";

void send_result(http_server::p_request req, int errcode, const char* msg, bool force_log = false) {
    Json::Value result;
    result["errcode"] = errcode;
    result["errMsg"] = msg;

    req->send_reply(200, to_cstr(result));

    if (errcode != 200) {
        auto uri = evhttp_request_get_evhttp_uri(req->req);
        auto query = evhttp_uri_get_query(uri);
        char buff[100];
        time_t now = time(NULL);
        strftime(buff,100,"%Y%m%d_%H%M%S",localtime(&now));
    	UTIL_LOG(E, "%s EPI_mi errcode:%d, msg:%s, query:%s", buff, errcode, msg, query);
    }
}

bool init_xiaomi() {
    g_https->handle("/bill/xiaomi", [](http_server::p_request req){
    	if (g_svrmgr->db_set >= 100) {
            send_result(req, 3515, "try later");
        	return;
    	}

        if (req->query["orderStatus"] != "TRADE_SUCCESS") {
            send_result(req, 200, "success", true);
            return;
        }

        int index = 0;
        stringstream ss;
        for (auto itr:req->query) {
            ++index;
            if (itr.first == "signature") {
                continue;
            }

            ss << itr.first << "=" << itr.second;
            if (index != req->query.size())
                ss << "&";
        }

        string sign = Sha1(ss.str().c_str(), appKey);
        if (sign != req->query["signature"]) {
            send_result(req, 1525, "invalid sign");
            return;
        }

        if (req->query["appId"] != appId) {
            send_result(req, 1515, "appId err");
            return;
        }

        string uid = req->query["uid"];

        int serverid;
        string account = fmt_cstr("mi-%s", uid.c_str());
        string orderId = fmt_cstr("mi-%s", req->query["orderId"].c_str());
        double payFee = atof(req->query["payFee"].c_str()) * g_cfg->Rate / 100;
        string machinecode;

        std::vector<std::string> vNote;
        split(req->query["cpUserInfo"], ",", vNote);
		if (vNote.size() != 2) {
            send_result(req, 1515, "cpUserInfo err");
            return;
		}
		serverid = atoi(vNote[0].c_str());
		machinecode = vNote[1];

        auto playerinfo = g_svrmgr->get_player_info(serverid, account);
        if (NULL == playerinfo) {
            send_result(req, 1520, "no player info");
            return;
        }

        g_svrmgr->post_order(serverid, orderId, playerinfo->playerid, payFee, machinecode, [req](bool ok){
            if (ok)
                send_result(req, 200, "success");
            else
                send_result(req, 1506, "error");
        });

    });

    return true;
}
